<script setup lang="ts">
import OsIcon from "@/components/OsIcon.vue";
import SortableGrid from "@/components/SortableGrid.vue";
import { move } from "@/utils/array";
import { setup } from "@/utils/setup.js";
import { useContentSize } from "@/utils/use";
import { Delete, Move, Renew, Restart } from "@vicons/carbon";
import { Compose16Regular } from "@vicons/fluent";
import { Add } from "@vicons/ionicons5";
import { useTimestamp } from "@vueuse/core";
import {
  NButton,
  NButtonGroup,
  NCard,
  NGridItem,
  NIcon,
  NSpace,
  NSpin,
  NText,
  NThing,
  NTime,
  NTooltip,
  NSwitch,
NEmpty,
} from "naive-ui";
import { computed, onUnmounted } from "vue";

const { configStore, storageStore, router, message } = setup();
const now = useTimestamp({ interval: 1000 });

const contentSize = useContentSize();
const blankCloudflareId = computed(() => {
  const cloudflareId = configStore.config?.cloudflareId;
  return cloudflareId === undefined || cloudflareId === "";
});
const hosts = computed(() => {
  return (
    configStore.config?.hosts.map((host, index) => {
      const storage = storageStore.cache[host.id];
      const restarting = host.restart > (storage?.uptime ?? 0);
      return { index, host, storage, restarting };
    }) ?? []
  );
});
const cols = computed(() => Math.round(contentSize.width.value / 450));

function gotoCloudflareIdSettings() {
  message.info("未设置 Cloudflare ID");
  router.push({ name: "settings", hash: "#cloudflareId" });
}

storageStore.startTimer();
onUnmounted(storageStore.stopTimer);
</script>

<template>
  <NButtonGroup style="margin: 16px 32px 16px 0; float: right">
    <NButton v-if="blankCloudflareId" @click="gotoCloudflareIdSettings()">
      监听日志
    </NButton>
    <NButton
      v-else
      tag="a"
      :href="`https://dash.cloudflare.com/${configStore.config?.cloudflareId}/workers/devs/view/ohmydev/production/logs/live`"
      target="_blank"
    >
      监听日志
    </NButton>
    <NButton type="primary" @click="router.push({ name: 'host' })">
      <template #icon>
        <NIcon :component="Add" />
      </template>
      新增
    </NButton>
  </NButtonGroup>
  <div style="padding: 16px 32px 16px 16px">
    <NCard v-if="hosts.length === 0">
      <NEmpty description="暂无主机，赶快创建吧">
        <template #extra>
          <NButton size="small" @click="router.push({ name: 'host' })">
            新增
          </NButton>
        </template>
      </NEmpty>
    </NCard>
    <SortableGrid
      v-else
      :cols="cols"
      :x-gap="16"
      :y-gap="12"
      @move="(oldIndex, newIndex) => move(configStore.config!.hosts, oldIndex, newIndex)"
    >
      <NGridItem v-for="{ index, host, storage, restarting } of hosts">
        <NCard hoverable>
          <NThing>
            <template #avatar>
              <OsIcon :value="storage?.os.name" :size="45" />
            </template>
            <template #header>{{ host.name }}</template>
            <template #header-extra>
              <NTooltip>
                <template #trigger>
                  <NButton
                    class="sortable-handle"
                    style="margin-right: 6px"
                    size="tiny"
                    text
                  >
                    <template #icon>
                      <NIcon color="rgb(51, 54, 57)" :component="Move" />
                    </template>
                  </NButton>
                </template>
                移动
              </NTooltip>
              <NTooltip>
                <template #trigger>
                  <NButton
                    style="margin-right: 6px"
                    size="tiny"
                    text
                    @click="() => (host.restart = Date.now())"
                  >
                    <template #icon>
                      <NSpin v-if="restarting" :size="14">
                        <template #icon>
                          <NIcon color="rgb(51, 54, 57)" :component="Restart" />
                        </template>
                      </NSpin>
                      <NIcon v-else :component="Restart" />
                    </template>
                  </NButton>
                </template>
                {{ restarting ? "重启中" : "重启" }}
              </NTooltip>
              <NTooltip>
                <template #trigger>
                  <NButton
                    style="margin-right: 6px"
                    size="tiny"
                    text
                    @click="
                      router.push({ name: 'host', query: { id: host.id } })
                    "
                  >
                    <template #icon>
                      <NIcon :component="Compose16Regular" />
                    </template>
                  </NButton>
                </template>
                编辑
              </NTooltip>
              <NTooltip>
                <template #trigger>
                  <NButton
                    size="tiny"
                    text
                    @click="configStore.config!.hosts.splice(index, 1)"
                  >
                    <template #icon>
                      <NIcon :component="Delete" />
                    </template>
                  </NButton>
                </template>
                删除
              </NTooltip>
            </template>
            <template #description>
              <div style="display: flex">
                <NText v-if="storage?.os !== undefined" :depth="3">
                  {{ storage.os.name }} {{ storage.os.release }}
                </NText>
                <NText
                  v-if="storage?.timestamp !== undefined"
                  style="margin-left: auto"
                  :depth="3"
                >
                  <NTime :time="storage.timestamp" :to="now" type="relative" />
                  更新
                </NText>
              </div>
            </template>
            <NSpace vertical>
              <!-- TODO 增加 ssh 项 -->
              <NCard
                v-for="crontab of host.crontabs"
                size="small"
                :title="'123'"
                embedded
                hoverable
              >
                <template #header-extra>
                  <NTooltip
                    v-if="storage?.crontabs[crontab.id]?.state === 'running'"
                  >
                    <template #trigger>
                      <NSpin style="margin-right: 6px" :size="14">
                        <template #icon>
                          <NIcon color="rgb(51, 54, 57)" :component="Renew" />
                        </template>
                      </NSpin>
                    </template>
                    运行中
                  </NTooltip>
                  <NSwitch size="small" v-model:value="crontab.enabled" />
                </template>
              </NCard>
            </NSpace>
          </NThing>
        </NCard>
      </NGridItem>
    </SortableGrid>
  </div>
</template>
